"""
系统状态管理模块
负责管理系统各种状态及其转换
"""

from enum import Enum
import threading
from typing import Callable, Dict, Any


class SystemState(Enum):
    """系统状态枚举"""
    IDLE = "idle"           # 空闲状态
    READY = "ready"         # 准备状态
    PLAYING = "playing"     # 播放状态
    PAUSED = "paused"       # 暂停状态
    ERROR = "error"         # 错误状态


class StateManager:
    """
    系统状态管理器
    负责管理系统状态及其转换
    """
    
    def __init__(self):
        """初始化状态管理器"""
        self._current_state = SystemState.IDLE
        self._previous_state = None
        self._state_lock = threading.Lock()
        self._state_listeners = []
        
    def get_current_state(self) -> SystemState:
        """获取当前系统状态"""
        with self._state_lock:
            return self._current_state
            
    def set_state(self, new_state: SystemState):
        """
        设置系统状态
        
        Args:
            new_state: 新的状态
        """
        with self._state_lock:
            self._previous_state = self._current_state
            self._current_state = new_state
            
        # 通知所有监听器状态已改变
        self._notify_state_change(self._previous_state, new_state)
        
    def can_transit_to(self, target_state: SystemState) -> bool:
        """
        检查是否可以转换到目标状态
        
        Args:
            target_state: 目标状态
            
        Returns:
            bool: 是否可以转换
        """
        current = self.get_current_state()
        
        # 定义合法的状态转换
        valid_transitions = {
            SystemState.IDLE: [SystemState.READY, SystemState.ERROR],
            SystemState.READY: [SystemState.PLAYING, SystemState.IDLE, SystemState.ERROR],
            SystemState.PLAYING: [SystemState.PAUSED, SystemState.IDLE, SystemState.ERROR],
            SystemState.PAUSED: [SystemState.PLAYING, SystemState.IDLE, SystemState.ERROR],
            SystemState.ERROR: [SystemState.IDLE, SystemState.READY]
        }
        
        return target_state in valid_transitions.get(current, [])
        
    def add_state_listener(self, listener: Callable[[SystemState, SystemState], None]):
        """
        添加状态变化监听器
        
        Args:
            listener: 状态变化监听回调函数
        """
        if listener not in self._state_listeners:
            self._state_listeners.append(listener)
            
    def remove_state_listener(self, listener: Callable[[SystemState, SystemState], None]):
        """
        移除状态变化监听器
        
        Args:
            listener: 要移除的监听器
        """
        if listener in self._state_listeners:
            self._state_listeners.remove(listener)
            
    def _notify_state_change(self, old_state: SystemState, new_state: SystemState):
        """
        通知状态变化
        
        Args:
            old_state: 旧状态
            new_state: 新状态
        """
        for listener in self._state_listeners:
            try:
                listener(old_state, new_state)
            except Exception as e:
                print(f"Error in state listener: {e}")


# 全局状态管理器实例
state_manager = StateManager()


def get_state_manager() -> StateManager:
    """
    获取全局状态管理器实例
    
    Returns:
        StateManager: 状态管理器实例
    """
    return state_manager